package cn.scau.server.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.scau.server.vo.EmpPermissionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 Swagger 请求
        if (request.getRequestURI().contains("/swagger-ui") ||
                request.getRequestURI().contains("/swagger-resources") ||
                request.getRequestURI().contains("/v2/api-docs") ||
                request.getRequestURI().contains("/webjars") ||
                request.getRequestURI().contains("/doc")) {
            return true;
        }

        // 特殊处理登录请求
        if (request.getRequestURI().equals("/mobileUser/login") || request.getRequestURI().equals("/pcUser/login")) {
            return true; // 登录请求不需要验证Token
        }

        // 1. 获取 Token
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Token is missing");
            return false;
        }
        System.out.println("token:" + token);
        // 2. 基于 Token 去 Redis 中获取用户信息
        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        System.out.println("key:" + key);
        // 3. 判断用户是否存在
        if (userMap == null || userMap.isEmpty()) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Token expired or invalid");
            return false;
        }

        // 4. 把查询到的 Hash 数据转成 DTO
        EmpPermissionVO empPermissionVO = BeanUtil.fillBeanWithMap(userMap, new EmpPermissionVO(), false);

        // 5. 存在，存入 ThreadLocal
        MobileUserHolder.saveEmpPermission(empPermissionVO);

        // 6. 刷新 Token 的过期时间
        stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.DAYS);

        // 7. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        MobileUserHolder.removeEmpPermission();
    }
}